﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using com.IronOne.BoardAppWeb.Lang;
using log4net;
using System.Web.Security;
using System.Configuration;
using com.IronOne.BoardAppWeb.Models.Auth;
using com.IronOne.BoardAppWeb.Models.Entity;
using com.IronOne.BoardAppWeb.Models;
using System.Net.Mail;
using System.Data.SqlClient;
using com.IronOne.BoardAppWeb.Models.General;
using com.IronOne.BoardAppWeb.Models.Admin;


namespace com.IronOne.BoardAppWeb.Controllers
{
    /// <summary>
    /// 
    ///  <title>BoardPAC AdminController</title>
    ///  <description>LogOnController for LogOn LogOff actions</description>
    ///  <copyRight>Copyright (c) 2011</copyRight>
    ///  <company>IronOne Technologies (Pvt)Ltd</company>
    ///  <createdOn>2011-10-18</createdOn>
    ///  <author></author>
    ///  <modification>
    ///     <modifiedBy></modifiedBy>
    ///      <modifiedDate></modifiedDate>
    ///     <description></description>
    ///  </modification>
    ///
    /// </summary>
    public class LogOnController : BaseController
    {
        // TODO : Remove reference LogManger.getEventLog().debug("sdfsdfsDF");
        // TODO : Rename logfileappender1 -> proper name

        protected static ILog EventLog = LogManager.GetLogger("EventLog");
        protected static ILog ErrorLog = LogManager.GetLogger("ErrorLog");

        AccountMembershipService MembershipService = new AccountMembershipService();
        FormsAuthenticationService FormsService = new FormsAuthenticationService();


        ///GetUserGuid return method
        ///<returns>
        ///Returns the GUID of the current user
        ///</returns>       
        ///<exception cref="">
        ///
        /// </exception>
        /// <remarks></remarks>
        public static Guid GetUserGuid()
        {
            EventLog.Info(String.Format(Resources.log_evt_entry_GetUserGuid, EventStatus.Debug.ToString()));

            Guid a = new Guid();
            try
            {
                a = (Guid)(Membership.GetUser().ProviderUserKey);
            }
            catch (Exception e)
            {
                ErrorLog.Error("0, " + "ERR, " + EventStatus.Failure.ToString() + ", LogOn" + ", GetUserGuid, Error =" + e);
                throw new GenException("err_111_sys");
            }
            return a;
        }


        /// <summary>
        /// Call at the first load of login page
        /// </summary>
        /// <param name="model"></param>
        /// <returns></returns>
        public ActionResult LogOn(LogOnModel model)
        {
            EventLog.Info(String.Format(Resources.log_evt_entry_LogOn, EventStatus.Entry.ToString(), Request.ServerVariables["REMOTE_ADDR"]));
            Logs.WriteLogToDb(String.Format(Resources.log_evt_entry_LogOn, EventStatus.Entry.ToString(), Request.ServerVariables["REMOTE_ADDR"]));

            // Check user is Authenticated
            if (User.Identity.IsAuthenticated)
            {
                //For Authenticated User
                EventLog.Info(String.Format(Resources.log_evt_success_LogOn, EventStatus.Success.ToString(), Request.ServerVariables["REMOTE_ADDR"], model.UserName, model.RememberMe));
                Logs.WriteLogToDb(String.Format(Resources.log_evt_success_LogOn, EventStatus.Success.ToString(), Request.ServerVariables["REMOTE_ADDR"], model.UserName, model.RememberMe));
                return GetFormatView("Home/Home.aspx");
            }
            else
            {
                try
                {
                    if (GetFormat().ToUpper().Equals("XML"))
                        throw new GenException("err_110");
                }

                catch (Exception e)
                {
                    ModelState.AddModelError("err", e);
                    ErrorLog.Error("0, " + "ERR, " + EventStatus.Failure.ToString() + ", LogOn" + ",LogOn, Client IP Address: " + Request.ServerVariables["REMOTE_ADDR"] + "," + e.Message);
                    EventLog.Info(String.Format(Resources.log_err_0_LogOn, EventStatus.Failure.ToString(), Request.ServerVariables["REMOTE_ADDR"], e.Message));
                    Logs.WriteLogToDb(String.Format(Resources.log_err_0_LogOn, EventStatus.Failure.ToString(), Request.ServerVariables["REMOTE_ADDR"], e.Message));
                }

                // Check the session and if it's not a new one and IsAuthenticated == false
                // definitely it's cause of a session expiration
                if (!Session.IsNewSession)  //if not a new session
                {
                    TempData["errMsg"] = "Your session has been expired!";
                }

                return GetFormatView("Auth/LogOn.aspx");
            }
        }


        ///LogOn Action Method
        ///<param name="model">LogOnModel</param>
        ///<param name="returnUrl">return URL</param>
        ///<returns>
        ///If successfully logged on goes to Default/Index or the return url
        ///</returns>       
        ///<exception cref="">
        ///Same view with the error
        /// </exception>
        /// <remarks></remarks>
        [HttpPost]
        public ActionResult LogOn(LogOnModel model, string returnUrl = "")
        {
            EventLog.Info(String.Format(Resources.log_evt_entry_LogOnPOST, EventStatus.Entry.ToString(), Request.ServerVariables["REMOTE_ADDR"], model.UserName, model.RememberMe, returnUrl));
            Logs.WriteLogToDb(String.Format(Resources.log_evt_entry_LogOnPOST, EventStatus.Entry.ToString(), Request.ServerVariables["REMOTE_ADDR"], model.UserName, model.RememberMe, returnUrl));

            //getting the deviceId
            RequestHeader req = GetHeaderLogDetails();
            String device = (req == null) ? device = null : device = req.deviceId;
            String mac = (req == null) ? mac = null : mac = req.macAddress;
            String IsiPadRequest = GetFormat() == "XML" ? "IPAD" : String.Empty;

            if (User.Identity.IsAuthenticated)
            {
                return GetFormatView("Home/Home.aspx");
            }


            try
            {
                if (model.UserName == null && model.Password == null) throw new GenException("err_100");
                else if (model.UserName == null) throw new GenException("err_101");
                else if (model.Password == null) throw new GenException("err_102");

                if (ModelState.IsValid)
                {   // TODO : get signed in user programmatically
                    MembershipUser mUser = Membership.GetUser(model.UserName);

                    // TODO : Comments
                    if (mUser != null)
                    {
                        if (mUser.IsLockedOut)
                        {
                            if (mUser.LastLockoutDate.AddMinutes(30) <= DateTime.Now)
                            {
                                mUser.UnlockUser();
                            }
                            throw new GenException("err_103");
                        }
                    }

                    if (MembershipService.ValidateUser(model.UserName, model.Password))
                    {
                        //EventLog.Info("0, " + "EVT, " + EventStatus.Debug.ToString() + ", LogOn" + ", LogOn Post,  Client IP Address: " + Request.ServerVariables["REMOTE_ADDR"] + ", MembershipService.ValidateUser true");
                        FormsService.SignIn(model.UserName, model.RememberMe);
                        //string a=User.Identity.Name;
                        EventLog.Info(String.Format(Resources.log_evt_success_LogOnPOST, EventStatus.Success.ToString(), Request.ServerVariables["REMOTE_ADDR"], model.UserName, IsiPadRequest));
                        Logs.WriteLogToDb(String.Format(Resources.log_evt_success_LogOnPOST, EventStatus.Success.ToString(), Request.ServerVariables["REMOTE_ADDR"], model.UserName, IsiPadRequest));
                        // Add format to session
                        Session.Add("fmt", Request.Params.Get("fmt"));

                        if (!String.IsNullOrEmpty(returnUrl))
                        {
                            return Redirect(returnUrl);
                        }
                        else
                        {
                            if (Session["fmt"] != null)
                            {
                                if (Request.Params.Get("fmt").ToUpper().Equals("XML"))
                                {
                                    using (BoardAppProductEntities entities = DataObjectFactory.CreateContext())
                                    {
                                        List<Guid> iPadAllowedRoleIds = new List<Guid> { Guid.Parse("874ca608-e39b-474e-b11e-37833fe8e8dc"), Guid.Parse("a0a8f9c4-68c6-4dfc-9066-7b8f3ccac220") };

                                        bool iPadAllowed = (from u in entities.Users
                                                            join ur in entities.aspnet_UsersInRoles on u.UserId equals ur.UserId
                                                            join r in entities.aspnet_Roles on ur.RoleId equals r.RoleId
                                                            where u.UserName.Equals(model.UserName) && iPadAllowedRoleIds.Contains(r.RoleId)
                                                            select u).Count() > 0 ? true : false;
                                        if (iPadAllowed)
                                        {
                                            ViewData["iPadLogOnResponse"] = RespondIpadonLogOn(model, device, mac);
                                        }
                                        else
                                        {
                                            ModelState.AddModelError("err", new GenException("err_112"));
                                        }
                                        return GetFormatView("Home/Home.aspx");
                                    }

                                }

                            }
                            else
                            {
                                return RedirectToAction("Index", "Default");
                            }
                        }
                    }
                    else
                    {
                        //EventLog.Info("104, " + "EVT, " + EventStatus.Debug.ToString() + ", LogOn" + ", LogOn, " + User.Identity.Name);
                        EventLog.Info(String.Format(Resources.log_err_104_LogOnPOST, EventStatus.Failure.ToString(), Request.ServerVariables["REMOTE_ADDR"], IsiPadRequest));
                        Logs.WriteLogToDb(String.Format(Resources.log_err_104_LogOnPOST, EventStatus.Failure.ToString(), Request.ServerVariables["REMOTE_ADDR"], IsiPadRequest));
                        throw new GenException("err_104");
                    }
                }
            }
            catch (GenException e)
            {
                EventLog.Info(String.Format(Resources.log_err_0_LogOnPOST, EventStatus.Failure.ToString(), Request.ServerVariables["REMOTE_ADDR"], e.Message) + " " + IsiPadRequest);
                Logs.WriteLogToDb(String.Format(Resources.log_err_0_LogOnPOST, EventStatus.Failure.ToString(), Request.ServerVariables["REMOTE_ADDR"], e.Message) + " " + IsiPadRequest);
                ErrorLog.Error(String.Format("0, " + "ERR, " + "{0}" + ", LogOn" + ",LogOn, Client IP Address: " + "{1}" + ", {2}", EventStatus.Failure.ToString(), Request.ServerVariables["REMOTE_ADDR"], e.Message));
                ModelState.AddModelError("err", e);

            }
            catch (SqlException e)
            {
                EventLog.Info(String.Format(Resources.log_err_105_LogOnPOST, EventStatus.Failure.ToString(), Request.ServerVariables["REMOTE_ADDR"]) + IsiPadRequest + " " + Resources.err_105);
                Logs.WriteLogToDb(String.Format(Resources.log_err_105_LogOnPOST, EventStatus.Failure.ToString(), Request.ServerVariables["REMOTE_ADDR"]) + IsiPadRequest + " " + Resources.err_105);
                ErrorLog.Error("105, " + "ERR, " + EventStatus.Failure.ToString() + ", LogOn" + ", LogOn, Client IP Address: " + Request.ServerVariables["REMOTE_ADDR"] + "," + Resources.err_105 + ", " + e);
                ModelState.AddModelError("err", new GenException("err_105"));
            }
            catch (Exception e)
            {
                EventLog.Info(String.Format(Resources.log_err_109_LogOnPOST, EventStatus.Failure.ToString(), Request.ServerVariables["REMOTE_ADDR"]) + IsiPadRequest + " " + Resources.err_109);
                Logs.WriteLogToDb(String.Format(Resources.log_err_109_LogOnPOST, EventStatus.Failure.ToString(), Request.ServerVariables["REMOTE_ADDR"]) + IsiPadRequest + " " + Resources.err_109);
                ErrorLog.Error("109, " + "ERR, " + EventStatus.Failure.ToString() + ", LogOn" + ", LogOn, Client IP Address: " + Request.ServerVariables["REMOTE_ADDR"] + ", " + Resources.err_109 + ", " + e);
                ModelState.AddModelError("err", new GenException("err_109"));
            }
            return GetFormatView("Auth/LogOn.aspx");
        }

        [Authorize]
        public ActionResult LogOff()
        {
            EventLog.Info(String.Format(Resources.log_evt_entry_LogOff, EventStatus.Entry.ToString(), User.Identity.Name));
            Logs.WriteLogToDb(String.Format(Resources.log_evt_entry_LogOff, EventStatus.Entry.ToString(), User.Identity.Name));
            //string a = Request.ServerVariables["REMOTE_ADDR"]; 

            try
            {
                if (GetFormat() == "XML")
                {
                    FormsService.SignOut();
                    Session.Abandon();
                    EventLog.Info(String.Format(Resources.log_evt_success_LogOff, EventStatus.Success.ToString(), User.Identity.Name) + " iPad");
                    Logs.WriteLogToDb(String.Format(Resources.log_evt_success_LogOff, EventStatus.Success.ToString(), User.Identity.Name) + " iPad");
                    return GetFormatView("Home/LogOff.aspx");
                }
                else
                {
                    FormsService.SignOut();
                    Session.Abandon();
                    EventLog.Info(String.Format(Resources.log_evt_success_LogOff, EventStatus.Success.ToString(), User.Identity.Name));
                    Logs.WriteLogToDb(String.Format(Resources.log_evt_success_LogOff, EventStatus.Success.ToString(), User.Identity.Name));
                }
            }
            catch (Exception e)
            {
                // User cannot logout at this moment.
                EventLog.Info(String.Format(Resources.log_err_117_LogOff, EventStatus.Failure.ToString(), User.Identity.Name) + Resources.err_117);
                Logs.WriteLogToDb(String.Format(Resources.log_err_117_LogOff, EventStatus.Failure.ToString(), User.Identity.Name) + Resources.err_117);
            }
            return RedirectToAction("LogOn", "LogOn");
        }

        [Authorize]
        public ActionResult NotAuthorized()
        {
            EventLog.Info(String.Format(Resources.log_evt_entry_NotAuthorized, EventStatus.Entry.ToString(), User.Identity.Name));
            return GetFormatView("Auth/NotAuthorized.aspx");
        }

        
        #region XmlActions

        //public ActionResult InitDeviceXml(string lastLoggedOnUser, string lastLoggedOnTime)
        //{
        //    EventLog.Info(String.Format(Resources.log_evt_entry_InitDeviceXml, EventStatus.Entry.ToString(), lastLoggedOnUser, lastLoggedOnTime));
        //    Logs.WriteLogToDb(String.Format(Resources.log_evt_entry_InitDeviceXml, EventStatus.Entry.ToString(), lastLoggedOnUser, lastLoggedOnTime));
        //    try
        //    {
        //        RequestHeader req = GetHeaderLogDetails();
        //        if (req == null)
        //            throw new GenException("err_151");

        //        PingToDatabase();

        //        //checking for deviceId contains in the list
        //        using (BoardAppProductEntities entities = DataObjectFactory.CreateContext())
        //        {
        //            if (req.deviceId != null)
        //            {
        //                int RegistreredDeviceCount = (from ud in entities.Devices
        //                                              where (ud.DeviceId.Equals(req.deviceId) && ud.Status == true)
        //                                              select ud).Count();
        //                if (RegistreredDeviceCount == 0)
        //                    throw new GenException("err_152");
        //            }
        //        }

        //        EventLog.Info(String.Format(Resources.log_evt_success_InitDeviceXml, EventStatus.Success.ToString(), req.clientAppVersion, req.clientTime, req.cooperateId, req.deviceId, lastLoggedOnUser, lastLoggedOnTime));
        //        Logs.WriteLogToDb(String.Format(Resources.log_evt_success_InitDeviceXml, EventStatus.Success.ToString(), req.clientAppVersion, req.clientTime, req.cooperateId, req.deviceId, lastLoggedOnUser, lastLoggedOnTime));
        //    }
        //    catch (GenException e)
        //    {
        //        EventLog.Info(String.Format(Resources.log_err_0_InitDeviceXml, EventStatus.Failure.ToString(), e.Message));
        //        Logs.WriteLogToDb(String.Format(Resources.log_err_0_InitDeviceXml, EventStatus.Failure.ToString(), e.Message));
        //        ErrorLog.Error("0, " + "ERR, " + EventStatus.Failure.ToString() + ", LogOn" + ", InitDeviceXml," + e.Message);
        //        ModelState.AddModelError("err", e);
        //    }
        //    catch (Exception e)
        //    {
        //        EventLog.Info(String.Format(Resources.log_err_109_InitDeviceXml, EventStatus.Failure.ToString(), User.Identity.Name) + Resources.err_109);
        //        Logs.WriteLogToDb(String.Format(Resources.log_err_109_InitDeviceXml, EventStatus.Failure.ToString(), User.Identity.Name) + Resources.err_109);
        //        ErrorLog.Error(EventStatus.Failure.ToString() + ", LogOn" + ",InitDeviceXml," + e.Message);
        //        ModelState.AddModelError("err", new GenException("err_109"));
        //        //TODO: Wrong Error code
        //    }

        //    // EventLog.Info(EventStatus.Success.ToString() + "," + this.ControllerContext.Controller.ToString() + ",InitDeviceXml,HeaderParams,ClientAppVersion," + req.clientAppVersion + "ClientTime," + req.clientTime + "CooperateId," + req.cooperateId + "DeviceId," + req.deviceId);
        //    return GetFormatView("Init/InitDevice.aspx");
        //}

        #region NonActions
        public IPADLogOnModel RespondIpadonLogOn(LogOnModel model, string deviceId, string macAddress)
        {
            EventLog.Info(String.Format(Resources.log_evt_entry_RespondIpadonLogOn, EventStatus.Entry.ToString(), User.Identity.Name, model.UserName, model.ReturnURL, deviceId));

            if (GetFormat().Equals("XML"))
            {
                using (BoardAppProductEntities entities = DataObjectFactory.CreateContext())
                {
                    IPADLogOnModel iPadLM = new IPADLogOnModel();
                    try
                    {
                        User user = (from u in entities.Users
                                     where u.UserName == model.UserName
                                     select u).ToList().First();


                        iPadLM.UserName = model.UserName;
                        iPadLM.Password = model.Password;
                        iPadLM.UserID = user.CustomUserId;
                        iPadLM.UserFullName = user.FirstName + " " + user.LastName;
                        iPadLM.UserRoles1 = new List<UserRole>();
                        iPadLM.roleOfuser = new List<RoleOfUser>();

                        //assuming that there would multiple roles for single user.
                        string[] userRoles = Roles.GetRolesForUser(model.UserName);

                        foreach (string item in userRoles)
                        {
                            aspnet_Roles aspRole = (from r in entities.aspnet_Roles
                                                    where r.RoleName == item
                                                    select r).First();

                            UserRole UR1 = new UserRole();
                            UR1.RoleID = aspRole.RoleId;
                            UR1.RoleDisplayName = aspRole.RoleName;
                            UR1.RoleActions = aspRole.Description;

                            iPadLM.UserRoles1.Add(UR1);
                        }

                        //assuming there would be only one category-wise role.
                        List<Access> rolesOfUser = (from a in entities.Accesses
                                                    where a.CustomUserId == user.CustomUserId
                                                    select a).ToList();

                        RoleOfUser roleOfUserModel = new RoleOfUser();

                        if (rolesOfUser.Any())
                        {
                            foreach (var item in rolesOfUser)
                            {

                                //CR1.CategoryID = item.CategoryId;
                                //CR1.CategoryName = item.Category.Name;
                                roleOfUserModel.RoleDisplayName = item.aspnet_Roles.RoleName;
                                roleOfUserModel.RoleActions = item.aspnet_Roles.Description;

                                iPadLM.roleOfuser.Add(roleOfUserModel);
                            }
                        }
                        /*
                        int RegistreredDeviceCount = (from ud in entities.UserDevices
                                                      where ((ud.CustomUserId == iPadLM.UserID) && ud.DeviceId.Equals(deviceId))
                                                      select ud).Count();
                        */
                        //checking for the device already registered
                        DefaultController d = new DefaultController();
                        d.IsDeviceAllowed(deviceId, macAddress);

                        int RegistreredDeviceCount = (from ud in entities.Devices
                                                      where ((ud.DeviceId.Equals(deviceId) || ud.MacAddress.Equals(macAddress)) && ud.Status == (byte)DeviceStatus.Active /*ud.Status == true*/)
                                                      select ud).Count();


                        if (RegistreredDeviceCount > 0)
                        {
                            iPadLM.DeviceRegStatus = "Device registered for the user";
                            EventLog.Info(String.Format(Resources.log_evt_success_RespondIpadonLogOn, EventStatus.Success.ToString(), User.Identity.Name, model.UserName, model.ReturnURL, deviceId, macAddress));

                        }
                        else
                        {
                            iPadLM.DeviceRegStatus = "Device not registered for the user";
                            ModelState.AddModelError("err", new GenException("err_153"));
                            FormsService.SignOut();
                            Session.Abandon();
                        }

                    }


                    catch (Exception e)
                    {
                        EventLog.Info(String.Format(Resources.log_err_115_RespondIpadonLogOn, EventStatus.Failure.ToString(), User.Identity.Name, e.Message));
                        EventLog.Error("0, " + "ERR, " + EventStatus.Debug.ToString() + ", LogOn" + ", RespondIpadonLogOn, " + e.Message);
                        ErrorLog.Error("0, " + "ERR, " + EventStatus.Failure.ToString() + ", LogOn" + ", RespondIpadonLogOn," + e.Message);
                        ModelState.AddModelError("err", e);
                    }

                    //ViewData["iPadLogOnResponse"] = iPadLM;
                    return iPadLM;
                }
            }
            return null;
        }
        #endregion NonActions

        #endregion XmlActions

        #region PasswordManagement

        #region AlertPasswordExpiry
        public string AlertLoginExpiry()
        {
            string alert = string.Empty;
            try
            {
                //EventLog.Info(String.Format(Resources.log_evt_entry_AlertLoginExpiry, EventStatus.Entry.ToString(), User.Identity.Name));

                MembershipUser mUser = Membership.GetUser();
                if (mUser != null)
                {
                    if (mUser.LastPasswordChangedDate.AddDays(int.Parse(ConfigurationManager.AppSettings["PasswordExpiryPeriod"]) - int.Parse(ConfigurationManager.AppSettings["PasswordExpiryAlertPeriod"])) <= DateTime.Now)
                    {
                        int expiryAlertdays = (mUser.LastPasswordChangedDate.AddDays(int.Parse(ConfigurationManager.AppSettings["PasswordExpiryPeriod"])) - DateTime.Now).Days;
                        if (expiryAlertdays > 0)
                        {
                            alert = String.Format(Resources.info_PasswordExpirywarning, expiryAlertdays.ToString());
                        }
                        else
                        {
                            alert = Resources.info_PasswordExpiredMsg;
                            ViewData["PasswordLength"] = MembershipService.MinPasswordLength;
                            View("~/Views/HTML/Auth/ChangePassword.aspx", null);
                        }
                        EventLog.Info(String.Format(Resources.log_evt_success_AlertLoginExpiry, EventStatus.Success.ToString(), mUser.UserName));
                    }
                    else
                    {
                        alert = string.Empty;
                    }
                }
                else
                {
                    //throw new GenException(111, "Membership.GetUser() returned a  Null membership user object.");
                }
                //EventLog.Info(String.Format(Resources.log_evt_success_AlertLoginExpiry, EventStatus.Success.ToString(), User.Identity.Name));

            }
            catch (Exception e)
            {
                // Login expirity is not working at this moment.
                EventLog.Info(String.Format(Resources.log_err_380_AlertLoginExpiry, EventStatus.Failure.ToString(), User.Identity.Name) + Resources.err_380);
                ErrorLog.Info("380, " + "ERR, " + EventStatus.Failure.ToString() + ", Paper" + ", MoveUpPaper, " + User.Identity.Name + "," + e.Message);
                ModelState.AddModelError("err", e);
            }
            return alert;
        }
        #endregion AlertPasswordExpiry

        #region ChangePassword
        //[Authorize]
        //public ActionResult ChangePassword(ResetPasswordModel model)
        //{
        //    EventLog.Info(String.Format(Resources.log_evt_entry_ChangePassword, EventStatus.Entry.ToString(), User.Identity.Name));
        //    Logs.WriteLogToDb(String.Format(Resources.log_evt_entry_ChangePassword, EventStatus.Entry.ToString(), User.Identity.Name));
        //    String IsiPadRequest = GetFormat() == "XML" ? "IPAD" : String.Empty;
        //    string userName = User.Identity.Name.ToString();

        //    try
        //    {
        //        if (model.NewPassword == null && model.OldPassword == null && model.ConfirmPassword == null)
        //        {
        //            ViewData["PasswordLength"] = MembershipService.MinPasswordLength;
        //            return GetFormatView("Auth/ChangePassword.aspx");
        //        }
        //        else
        //        {
        //            userName = Request.Params.Get("userName");

        //            if (ModelState.IsValid)
        //            {
        //                if (MembershipService.ChangePassword(userName, model.OldPassword, model.NewPassword))
        //                {
        //                    EventLog.Info(String.Format(Resources.log_evt_success_ChangePassword, EventStatus.Entry.ToString(), User.Identity.Name, IsiPadRequest));
        //                    Logs.WriteLogToDb(String.Format(Resources.log_evt_success_ChangePassword, EventStatus.Entry.ToString(), User.Identity.Name, IsiPadRequest));
        //                    ModelState.AddModelError("err", new GenException("err_106"));
        //                    return GetFormatView("Auth/ChangePasswordSuccess.aspx");
        //                }
        //                else
        //                {
        //                    ModelState.AddModelError("err", new GenException("err_107"));
        //                }
        //            }
        //            else
        //            {
        //                string errorMessage = "";
        //                IEnumerable<ModelState> list = ModelState.Values.AsEnumerable();
        //                foreach (var item in list)
        //                {
        //                    if (item.Errors.Count != 0)
        //                    {
        //                        errorMessage = item.Errors[0].ErrorMessage.ToString();
        //                        break;
        //                    }
        //                }
        //                ModelState.AddModelError("err", new GenException("err_990", errorMessage));
        //            }

        //            ViewData["PasswordLength"] = MembershipService.MinPasswordLength;
        //        }
        //    }
        //    catch (Exception e)
        //    {
        //        EventLog.Info(String.Format(Resources.log_err_116_ChangePassword, EventStatus.Failure.ToString(), User.Identity.Name) + IsiPadRequest + " " + Resources.err_116);
        //        Logs.WriteLogToDb(String.Format(Resources.log_err_116_ChangePassword, EventStatus.Failure.ToString(), User.Identity.Name) + IsiPadRequest + " " + Resources.err_116);
        //        // System can not change the password at this momunt. - 116
        //        ErrorLog.Info("116, " + "ERR, " + EventStatus.Failure.ToString() + ", LogOn" + ", ChangePassword, " + User.Identity.Name + "," + e.Message);
        //        ModelState.AddModelError("err", new GenException("err_116"));
        //    }
        //    return GetFormatView("Auth/ChangePassword.aspx", model);
        //}
        #endregion ChangePassword


        //public ActionResult ResetPasswordbyAdmin(string username)
        //{
        //    EventLog.Info(String.Format(Resources.log_evt_entry_ResetPasswordbyAdmin, EventStatus.Entry.ToString(), User.Identity.Name));
        //    Logs.WriteLogToDb(String.Format(Resources.log_evt_entry_ResetPasswordbyAdmin, EventStatus.Entry.ToString(), User.Identity.Name));

        //    MembershipUser user = Membership.GetUser(username);
        //    string newPassword = user.ResetPassword();
        //    //string newPassword = ConfigurationManager.AppSettings["newUserPW"].ToString();
        //    user.ChangePassword(newPassword, ConfigurationManager.AppSettings["newUserPW"].ToString());

        //    using (BoardAppProductEntities ntb = new BoardAppProductEntities())
        //    {
        //        User userentityforPRmail = ntb.Users.Where(m => m.Status != 0 && m.UserName == username).ToList().FirstOrDefault();


        //        if (!string.IsNullOrWhiteSpace(userentityforPRmail.BoardEmail))
        //        {
        //            try
        //            {
        //                MailMessage mail = new MailMessage();
        //                //set the addresses
        //                mail.From = new MailAddress(ConfigurationManager.AppSettings["EmailUserName"].ToString());
        //                mail.To.Add(userentityforPRmail.BoardEmail);

        //                mail.Subject = "Password has reset";
        //                mail.Body = "Dear " + userentityforPRmail.FirstName + ",\n" + "Your Password has been reset by the Administrator." + " \nNew Password is: " + ConfigurationManager.AppSettings["newUserPW"].ToString();
        //                //mail.IsBodyHtml = true;

        //                SmtpClient client;
        //                bool sslOn = Convert.ToBoolean(ConfigurationManager.AppSettings["SSL_Enable"]);
        //                if (sslOn)
        //                {
        //                    client = Settings.GetEmailConfigs(true); // SSL enabled  
        //                }
        //                else
        //                {
        //                    client = Settings.GetEmailConfigs(false); // SSL not enabled
        //                }

        //                //var client = new SmtpClient(ConfigurationManager.AppSettings["EmailClient"].ToString(), Convert.ToInt32(ConfigurationManager.AppSettings["EmailPort"].ToString()))
        //                //{
        //                //    Credentials = new NetworkCredential(ConfigurationManager.AppSettings["EmailUserName"].ToString(), ConfigurationManager.AppSettings["EmailPassword"].ToString())
        //                //    //, EnableSsl = true
        //                //};

        //                client.Send(mail);
        //                mail.Dispose();
        //                EventLog.Info(String.Format(Resources.log_evt_success_ResetPasswordbyAdmin, EventStatus.Entry.ToString(), User.Identity.Name));
        //                Logs.WriteLogToDb(String.Format(Resources.log_evt_success_ResetPasswordbyAdmin, EventStatus.Entry.ToString(), User.Identity.Name));
        //            }
        //            catch (Exception e)
        //            {
        //                //log.Error(LogPoint.Failure.ToString() + "," + this.ControllerContext.Controller.ToString() + ",ResetPasswordbyAdmin," + User.Identity.Name);
        //                //ModelState.AddModelError("err", new GenException("err_108"));
        //                EventLog.Info(String.Format(Resources.log_err_1200_ResetPasswordbyAdmin, EventStatus.Failure.ToString(), User.Identity.Name, Resources.err_108));
        //                Logs.WriteLogToDb(String.Format(Resources.log_err_1200_ResetPasswordbyAdmin, EventStatus.Failure.ToString(), User.Identity.Name, Resources.err_108));
        //                ErrorLog.Info("108, " + "ERR, " + EventStatus.Failure.ToString() + ", LogOn" + ", ResetPasswordbyAdmin, " + User.Identity.Name + "," + e.Message);
        //                TempData["Error"] = Resources.err_108.ToString();
        //                //return GetFormatView("ErrorView.aspx");
        //            }
        //        }
        //    }
        //    return RedirectToAction("ViewUsers", "UserMgt");
        //}
        
        #endregion PasswordManagement
    }
}
